<script setup lang="ts">
import { PropType, reactive, ref, watch, unref } from 'vue'
import { Descriptions } from '@/components/Descriptions'
import { useI18n } from '@/hooks/web/useI18n'
import { ElTag, ElButton, ElMessageBox } from 'element-plus'
import { ucUserDeptListAdminApi, ucUserDeptSetAdminApi, ucUserDeptDelApi } from '@/api/uc/userDept'
import { ucDeptListApi } from '@/api/uc/dept'
import {
  ucUserRoleListAdminApi,
  ucUserRoleSetAdminApi,
  ucUserRoleDelAdminApi
} from '@/api/uc/userRole'
import { ucOrgRoleListAdminApi } from '@/api/uc/orgRole'
import { ContentWrap } from '@/components/ContentWrap'
import { Table } from '@/components/Table'
import { Dialog } from '@/components/Dialog'
import { useTable } from '@/hooks/web/useTableTest'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import TreeDept from './TreeDept.vue'
import TreeRole from './TreeRole.vue'

const { t } = useI18n()

const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<any>>,
    default: () => null
  },
  detailSchema: {
    type: Array as PropType<DescriptionsSchema[]>,
    default: () => []
  }
})

/****************************** 相关部门列表 start ******************************/
const userDeptTable = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: ucUserDeptListAdminApi,
  response: {
    data: 'data',
    count: 'count'
  }
})

const userDeptCrudSchemas = reactive<CrudSchema[]>([
  {
    field: 'dept_name',
    label: '部门名称',
    search: {
      show: false
    },
    form: {
      show: false
    },
    table: {
      show: true
    }
  },
  {
    field: 'action',
    width: 120,
    fixed: 'right',
    label: t('tableDemo.action'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  }
])
const userDeptRegister = userDeptTable.register
const userDeptTableObject = userDeptTable.tableObject
const userDeptMethods = userDeptTable.methods
const userDeptAllSchemas = useCrudSchemas(userDeptCrudSchemas).allSchemas
const userDeptGetList = userDeptMethods.getList
/****************************** 相关部门列表 end ******************************/

/****************************** 相关角色列表 start ******************************/
const userRoleTable = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: ucUserRoleListAdminApi,
  response: {
    data: 'data',
    count: 'count'
  }
})

const userRoleCrudSchemas = reactive<CrudSchema[]>([
  {
    field: 'role_name',
    label: '角色名称',
    search: {
      show: false
    },
    form: {
      show: false
    },
    table: {
      show: true
    }
  },
  {
    field: 'action',
    width: 120,
    fixed: 'right',
    label: t('tableDemo.action'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  }
])
const userRoleRegister = userRoleTable.register
const userRoleTableObject = userRoleTable.tableObject
const userRoleMethods = userRoleTable.methods
const userRoleAllSchemas = useCrudSchemas(userRoleCrudSchemas).allSchemas
const userRoleGetList = userRoleMethods.getList
/****************************** 相关角色列表 end ******************************/

/****************************** 和树结构相关 start ******************************/
const treeDeptRef = ref<ComponentRef<typeof TreeDept>>()
const treeDeptProps = ref({})
const treeDeptData = ref([])
const treeDeptKey = ref('')

const treeRoleRef = ref<ComponentRef<typeof TreeRole>>()
const treeRoleProps = ref({})
const treeRoleData = ref([])
const treeRoleKey = ref('')
/****************************** 和树结构相关 end ******************************/

const actionType = ref('')
const dialogVisible = ref(false)
const dialogTitle = ref('')
const action = async (type: string, row: any = {}) => {
  actionType.value = type
  switch (type) {
    case 'setDept':
      dialogTitle.value = '关联部门'
      dialogVisible.value = true
      treeDeptProps.value = {
        children: 'children',
        label: 'dept_name',
        disabled: 'disabled'
      }
      treeDeptKey.value = 'dept_id'
      let deptTreeRes = await ucDeptListApi({ org_id: props.currentRow.org_id })
        .catch(() => {})
        .finally(() => {})
      if (deptTreeRes) {
        treeDeptData.value = deptTreeRes.data
      }
      let ids: any = []
      userDeptTableObject.tableList.forEach((item) => {
        ids.push(item.dept_id)
      })
      const treeDept = unref(treeDeptRef)
      treeDept!.setCheckedKeys(ids)
      break
    case 'delDept':
      ElMessageBox.confirm('确定要删除这个部门？', '删除部门', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          ucUserDeptDelApi({
            user_dept_id: row.user_dept_id
          })
            .catch(() => {})
            .finally(() => {
              userDeptGetList()
            })
        })
        .catch(() => {
          console.log('这里是取消confirm弹框')
        })
      break
    case 'setRole':
      dialogTitle.value = '关联角色'
      dialogVisible.value = true
      treeRoleProps.value = {
        children: 'children',
        label: 'role_name',
        disabled: 'disabled'
      }
      treeRoleKey.value = 'role_id'
      let RoleTreeRes = await ucOrgRoleListAdminApi({
        org_id: props.currentRow.org_id,
        add_is_sys: true
      })
        .catch(() => {})
        .finally(() => {})
      if (RoleTreeRes) {
        console.log('RoleTreeRes', RoleTreeRes)
        treeRoleData.value = RoleTreeRes.data
      }
      let role_ids: any = []
      userRoleTableObject.tableList.forEach((item) => {
        role_ids.push(item.role_id)
      })
      const treeRole = unref(treeRoleRef)
      treeRole!.setCheckedKeys(role_ids)
      break
    case 'delDept':
      ElMessageBox.confirm('确定要删除这个部门？', '删除部门', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          ucUserDeptDelApi({
            user_dept_id: row.user_dept_id
          })
            .catch(() => {})
            .finally(() => {
              userDeptGetList()
            })
        })
        .catch(() => {
          console.log('这里是取消confirm弹框')
        })
      break
    case 'delRole':
      ElMessageBox.confirm('确定要删除这个角色？', '删除角色', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          ucUserRoleDelAdminApi({
            user_role_id: row.user_role_id
          })
            .catch(() => {})
            .finally(() => {
              userRoleGetList()
            })
        })
        .catch(() => {
          console.log('这里是取消confirm弹框')
        })
      break
    default:
      console.log('未知类型')
  }
}

/****************************** 监听设置固定条件 start ******************************/
const newFixedSearch = ref({})
watch(
  () => props.currentRow,
  (val: any) => {
    if (!val) return
    // 设置固定条件
    newFixedSearch.value = {
      user_id: val.user_id, //用户
      org_id: val.org_id
    }
    userDeptTableObject.fixedSearch = newFixedSearch.value
    userRoleTableObject.fixedSearch = newFixedSearch.value
  },
  {
    deep: true,
    immediate: true
  }
)
/****************************** 监听设置固定条件 start ******************************/

/****************************** 初始化 start ******************************/
// userDeptGetList() //查询相关组织列表
const init = async () => {
  // 获取这个用户的所有部门
  await userDeptGetList()
  // 获取这个用户的所有角色
  await userRoleGetList()
}
init()
/****************************** 初始化 end ******************************/

const save = async (type: string) => {
  switch (type) {
    case 'setDept':
      const treeDept = unref(treeDeptRef)
      const ids = treeDept!.getCheckedKeys()
      const userDeptSetRes = await ucUserDeptSetAdminApi({
        org_id: props.currentRow.org_id,
        user_id: props.currentRow.user_id,
        ids
      })
        .catch(() => {})
        .finally(() => {
          // loading.value.save = false
        })
      if (userDeptSetRes) {
        // 关闭 dialog
        // 成功 刷新列表查询
        userDeptGetList()
        dialogVisible.value = false
      }
      break
    case 'setRole':
      const treeRole = unref(treeRoleRef)
      const role_ids = treeRole!.getCheckedKeys()
      const userRoleSetRes = await ucUserRoleSetAdminApi({
        org_id: props.currentRow.org_id,
        user_id: props.currentRow.user_id,
        ids: role_ids
      })
        .catch(() => {})
        .finally(() => {
          // loading.value.save = false
        })
      if (userRoleSetRes) {
        // 关闭 dialog
        // 成功 刷新列表查询
        userRoleGetList()
        dialogVisible.value = false
      }
      break
    default:
      console.log('未知类型')
  }
}
</script>

<template>
  <Descriptions :schema="detailSchema" :data="currentRow || {}">
    <template #is_owner="{ row }: { row: any }">
      <ElTag :type="row.is_owner === '1' ? 'success' : row.is_owner === '0' ? 'warning' : 'danger'">
        {{
          row.is_owner === '1' ? '管理员' : row.is_owner === '0' ? '成员' : t('tableDemo.commonly')
        }}
      </ElTag>
    </template>
    <template #is_stop="{ row }: { row: any }">
      <ElTag :type="row.is_stop === '0' ? 'success' : row.is_stop === '1' ? 'warning' : 'danger'">
        {{ row.is_stop === '0' ? '启用' : row.is_stop === '1' ? '停用' : t('tableDemo.commonly') }}
      </ElTag>
    </template>
  </Descriptions>

  <div class="p-10px">
    <ContentWrap title="当前组织所属部门">
      <div class="mb-10px">
        <ElButton type="primary" @click="action('setDept', {})">设置部门</ElButton>
      </div>
      <Table
        v-model:pageSize="userDeptTableObject.pageSize"
        v-model:currentPage="userDeptTableObject.currentPage"
        :columns="userDeptAllSchemas.tableColumns"
        :data="userDeptTableObject.tableList"
        :loading="userDeptTableObject.loading"
        :pagination="{
          total: userDeptTableObject.count
        }"
        @register="userDeptRegister"
        :selection="false"
      >
        <template #action="{ row }">
          <ElButton type="warning" @click="action('delDept', row)" title="删除"> 删除 </ElButton>
        </template>
      </Table>
    </ContentWrap>
  </div>

  <div class="p-10px">
    <ContentWrap title="当前组织所属角色">
      <div class="mb-10px">
        <ElButton type="primary" @click="action('setRole', {})">设置角色</ElButton>
      </div>
      <Table
        v-model:pageSize="userRoleTableObject.pageSize"
        v-model:currentPage="userRoleTableObject.currentPage"
        :columns="userRoleAllSchemas.tableColumns"
        :data="userRoleTableObject.tableList"
        :loading="userRoleTableObject.loading"
        :pagination="{
          total: userRoleTableObject.count
        }"
        @register="userRoleRegister"
        :selection="false"
      >
        <template #action="{ row }">
          <ElButton type="warning" @click="action('delRole', row)" title="删除"> 删除 </ElButton>
        </template>
      </Table>
    </ContentWrap>
  </div>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <TreeDept
      v-if="actionType == 'setDept'"
      :treeProps="treeDeptProps"
      :treeData="treeDeptData"
      :nodeKey="treeDeptKey"
      ref="treeDeptRef"
    />

    <TreeRole
      v-if="actionType == 'setRole'"
      :treeProps="treeRoleProps"
      :treeData="treeRoleData"
      :nodeKey="treeRoleKey"
      ref="treeRoleRef"
    />

    <template #footer>
      <ElButton v-if="actionType == 'setDept'" type="primary" @click="save('setDept')">
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton v-if="actionType == 'setRole'" type="primary" @click="save('setRole')">
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
</template>
